package cn.kailangtu.myapplication.tools;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.SystemClock;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AppUtils {

    private static AppUtils instance;
    private static Context mContext;
    private static Application mApplication;
    private boolean isCanBzAppIsTop = true;
    private int noBzAppIsTopTimeCur = 0;
    private int noBzAppIsTopTimeAll = 60 * 1000;
    private ExecutorService cacheThreadPool;


    public static AppUtils getInstance(){
        if(instance == null){
            instance = new AppUtils();
        }
        return instance;
    }

    private AppUtils(){}


    public void startBzAppIsTopThread(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (isCanBzAppIsTop) {
                        //L.smEE("保证APP一直显示线程，开始：" + Thread.currentThread().getName());
                        while (isCanBzAppIsTop) {
                            int time = 5 * 1000;
                            noBzAppIsTopTimeCur += time;
                            SystemClock.sleep(time);
                            if (isCanBzAppIsTop) {
                                if (noBzAppIsTopTimeCur > noBzAppIsTopTimeAll) {
                                    setTopApp();
                                    isSetTopAppThtead();
                                    restartBzAppIsTopTimer();
                                }
                            }
                        }
                        //L.smEE("保证APP一直显示线程，结束：" + Thread.currentThread().getName());
                    }
                }
            }
        }).start();
    }

    private void isSetTopAppThtead(){
        getExecutorService().execute(new Runnable() {
            @Override
            public void run() {
                SystemClock.sleep(3 * 1000);
                isSetTopApp();
            }
        });
    }

    public void restartBzAppIsTopTimer() {
        noBzAppIsTopTimeCur = 0;
        noBzAppIsTopTimeAll = 60 * 1000;
        isCanBzAppIsTop = true;
    }

    /**
     * 将本应用置顶到最前端
     * 当本应用位于后台时，则将它切换到最前端
     */
    private void setTopApp() {
//        L.smEE("将本应用置顶到最前端，开始");
        try {
            String packageName = PackageUtils.getInstance().get获取App包名();
            /**获取ActivityManager*/
            ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
            /**获得当前运行的task(任务)*/
            List<ActivityManager.RunningTaskInfo> taskInfoList = activityManager.getRunningTasks(100);
            for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                /**找到本应用的 task，并将它切换到前台*/
                if (taskInfo.topActivity.getPackageName().equals(packageName) || taskInfo.baseActivity.getPackageName().equals(packageName)) {
                    activityManager.moveTaskToFront(taskInfo.id, 0);
//                    L.smEE("将本应用置顶到最前端，执行");
                    break;
                }
            }
        } catch (Exception e) {
//            Logger.e(e, "将本应用置顶到最前端，异常！");
        }
    }

    public void setContext(Context con){
        mContext = con;
        cacheThreadPool = Executors.newCachedThreadPool();
    }

    public void setApplication(Application app)
    {
        mApplication = app;
    }

    public Context getContext(){
        return mContext;
    }

    public Application getApplication(){
        return mApplication;
    }

    public ExecutorService getExecutorService(){
        return cacheThreadPool;
    }

    private int noSetTopApp = 0;
    private void isSetTopApp(){
        boolean topActivity = isRunningForeground();
        if (topActivity) {
            noSetTopApp = 0;
        } else {
            noSetTopApp++;
        }
        if (noSetTopApp >= 3) {
           // L.smEE("APP长时间未处于前台重启，已触发！");
            // 3秒一次，连续检测到5次设备未处于购买状态再重启(多次检测是否处于购买状态)
            int disOpeningCount = 0;
            while (true) {

               // EventBus.getDefault().post(new CommandAppRestartEvent());
                SystemClock.sleep(3 * 1000);
            }
        }
    }

    /**
     * 判断当前应用是否在前台
     * 系统签名的应用，可以获取其他应用进程，当前是否在前台 ，非系统签名应用只能获取自己的
     */
    private boolean isRunningForeground() {
        try {
            ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
            if (runningAppProcesses == null) {
                return false;
            }
            String packageName = PackageUtils.getInstance().get获取App包名();
            for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : runningAppProcesses) {
                String strProcessName = runningAppProcessInfo.processName;
                int importance = runningAppProcessInfo.importance;
                if (packageName.equalsIgnoreCase(strProcessName) &&
                        importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    return true;
                }
            }
            return  false;
        } catch (Exception e) {
            //Logger.e(e, "判断本应用是否在最前端，异常！");
            return false;
        }
    }
}
